package cn.micai.base.io;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.IOException;
import java.io.StringWriter;

/**
 * @Auther: zhaoxinguo
 * @Date: 2018/8/23 12:03
 * @Description: 使用jackson-all.1.7.6.jar工具包实现将对象序列化为JSON格式、JSON格式反序列化为对象
 */
public class JacksonAllSerializeDeserializeMain {

    /**
     * 将Java对象employee序列化成为JSON格式
     * @param employee
     * @return
     */
    public static String serialize(Employee employee){
        // JSON对象序列化
        String employeeJson = null;
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            StringWriter stringWriter = new StringWriter();
            JsonGenerator jsonGenerator = new JsonFactory().createJsonGenerator(stringWriter);
            objectMapper.writeValue(jsonGenerator, employee);
            jsonGenerator.close();
            employeeJson = stringWriter.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return employeeJson;
    }

    /**
     * 将JSON格式反序列化为employee对象
     * @param employeeJson
     * @return
     */
    public static Employee deserialize(String employeeJson) {
        try {
            ObjectMapper objectMapper = new ObjectMapper();
            return objectMapper.readValue(employeeJson, Employee.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String [] args) {

        Employee employee = new Employee();
        employee.setEmployeeId(1);
        employee.setEmployeeName("赵新国");
        employee.setDepartment("软件工程师");
        // 序列化
        String serialize = serialize(employee);
        System.out.println(serialize);
        // 反序列化
        Employee deserialize = deserialize(serialize);
        System.out.println(deserialize);

    }

}
